<!--
 * @Descripttion: 订单详情
 * @version:
 * @Author: lehaixia
 * @Date: 2022-10-28 09:36:17
 * @LastEditors: lehaixia
 * @LastEditTime: 2023-03-03 15:40:19
-->
<template>
  <div class="content">
    <ComHeader id="oHeader" :arrow="true" :border="barOpacity===1" :title-left="false" :show-statusbar="true" title="订单详情" :bg-color="headerBgColor" @get-height="handleHeadHeight" />
    <div class="detail-item" :class="{'pb58':isEdit}">
      <div class="d-progress" @click="jumpToProgressDetail">
        <div class="d-title d-mb10">订单进度</div>
        <div class="d-desc">{{ progressDesc }}</div>
      </div>
      <div v-if="isDealer" class="d-price">
        <div class="d-title">订单总价</div>
        <div class="d-fee">￥{{ detailInfo.orderTotalAmount }}</div>
      </div>
      <div class="d-base">
        <div class="d-base-head">
          <div class="d-title">订单信息</div>
        </div>
        <div class="d-base-con">
          <div class="d-base-con-row"><div class="d-title">采购单号</div> <div class="d-desc">{{ detailInfo.orderCode }}</div></div>
          <div class="d-base-con-row"><div class="d-title">接单号</div><div class="d-desc">{{ detailInfo.receiptNumber }}</div></div>
          <div class="d-base-con-row"><div class="d-title">顾客姓名</div><div class="d-desc">{{ detailInfo.optyCustomerName }}</div></div>
          <div class="d-base-con-row"><div class="d-title">顾客电话</div> <div class="d-desc">{{ detailInfo.optyCustomerPhone }}</div></div>
          <div class="d-base-con-row"><div class="d-title">订单品类</div>  <div class="d-desc">{{ getDictName('CRM_CATEGORY_SELECTION',detailInfo.orderType) }}</div></div>
          <div class="d-base-con-row"> <div class="d-title">设计师</div><div class="d-desc">{{ detailInfo.designerName }}</div></div>
          <div class="d-base-con-row"> <div class="d-title">送达方</div><div class="d-desc">{{ detailInfo.sdfAccountDesc }}</div>
          </div>
          <div v-if="detailInfo.isUpSample === 1" class="d-base-con-row">
            <!-- 上样订单:是否锁定值为“是”时可编辑-->
            <div class="d-title">是否提前进行外购件采购</div>
            <div v-if="isEdit && detailInfo.isSapLock===1" class="d-radio">
              <van-radio-group
                v-model="isPriceOutsourcing"
                direction="horizontal"
                checked-color="rgba(0, 200, 180, 1)"
                :disabled="!isEdit"
              >
                <van-radio v-for="r in radioList" :key="r.value" :name="r.value">
                  <template #default><span class="d-radio-title d-title">{{ r.name }}</span></template>
                  <template #icon="props">
                    <img class="img-icon" :src="props.checked ? activeIcon : inactiveIcon">
                  </template>
                </van-radio>
              </van-radio-group>
            </div>
            <div v-else class="d-desc">{{ isPriceOutsourcing===1?'是':detailInfo.isPriceOutsourcing===0?'否':'' }}</div>
          </div>
          <div class="d-base-con-row"><div class="d-title">下单人</div><div class="d-desc">{{ detailInfo.createBy }}</div></div>
          <div class="d-base-con-row"><div class="d-title">下单日期</div> <div class="d-desc">{{ detailInfo.createTime }}</div></div>
          <div class="d-base-con-row"><div class="d-title">设计师QQ</div><div class="d-desc">{{ detailInfo.designerQq }}</div></div>
          <div class="d-base-con-row"><div class="d-title">方案ID</div> <div class="d-desc">{{ detailInfo.schemeId }}</div></div>
          <div class="d-base-con-row"><div class="d-title">是否优选单</div>  <div class="d-desc">{{ whetherName(detailInfo.isParticular) }}</div></div>
          <div class="d-base-con-row"> <div class="d-title">专卖店</div><div class="d-desc">{{ detailInfo.shopName }}</div></div>
          <div class="d-base-con-row"><div class="d-title">采购类型</div><div class="d-desc">{{ isUpSample }}</div></div>
          <div v-if="detailInfo.isUpSample === 1" class="d-base-con-row"><div class="d-title">是否锁定</div><div class="d-desc">{{ whetherName(detailInfo.isSapLock === 1) }}</div></div>
          <div class="d-base-con-row"><div class="d-title">客户地址</div>  <div class="d-desc">{{ detailInfo.fullAddr }}</div></div>
          <div class="d-base-con-row"> <div class="d-title">备注</div><div class="d-desc">{{ detailInfo.remark }}</div></div>
        </div>
      </div>
      <div v-for="(r, i) in productList" :key="i" class="d-base">
        <div class="d-base-head">
          <div class="d-title">{{ r.kjlProdName }}</div>
        </div>
        <div class="d-base-con">
          <div class="d-base-con-row"><div class="d-title-small">柜号</div> <div class="d-desc-small">{{ r.partNumber }}</div></div>
          <div v-if="isDealer" class="d-base-con-row"><div class="d-title-small">整体总价</div> <div class="d-desc-small">{{ r.cdsTotalPrice }}</div></div>
          <div class="d-base-con-row"><div class="d-title-small">产品主色</div> <div class="d-desc-small">{{ r.kjlProdColor }}</div></div>
          <div class="d-base-con-row"><div class="d-title-small">产品终止</div> <div class="d-desc-small" :class="{'d-red': r.state === 'TerminationProducts'}">{{ r.state === 'TerminationProducts' ? '是':'否' }}</div></div>
          <div v-if="isDealer" class="d-base-con-row">
            <div />
            <div class="d-base-btn" @click="jumpToQuoteDetail(r)">
              <span>查看报价明细</span>
            </div>
          </div>
        </div>
      </div>

      <div v-if="isEdit" class="d-btn-con">
        <div class="d-btn" @click="handlePriceConfirm(-1)">不通过</div>
        <div class="d-btn" @click="handlePriceConfirm(1)">通过</div>
      </div>
    </div>

    <PopField
      v-if="showPop"
      v-model="offerPriceConfirmSuggestion"
      title="报价不通过原因"
      :show.sync="showPop"
      :required="true"
      :rules="[{ required: true, message: '不通过原因' }]"
      @input="handlePriceFail"
    />
  </div>
</template>
<script>
import activeIcon from '@/assets/category/radio-active.png'
import inactiveIcon from '@/assets/category/radio-inactive.png'
import arrowIcon from '@/assets/category/ic_arrow.png'
import { getOrderDetail, getOrderProductList, querySdf, priceConfirm, havePosition } from '@/apis/purOrder'
import { json2FormData } from '@/utils'
import { getDictByPatchType } from '@/apis/dataDict'
import { bus } from '@/utils/bus'
import PopField from '@/components/PopField'

export default {
  name: 'PurOrderDetail',
  components: {
    PopField
  },
  data() {
    return {
      activeIcon,
      inactiveIcon,
      arrowIcon,
      headHeight: 50,
      radio: 1,
      radioList: [{ id: 1, name: '是', value: 1 }, { id: 1, name: '否', value: 0 }],
      productList: [], // 产品列表
      detailInfo: '', // 详情
      isPriceOutsourcing: 0, // 是否提前进行外购件采购
      sdfAccount: [],
      submiting: false,
      isDealer: false, // 是否经销商
      isEdit: false, // 是否编辑 用户是经销商且经销商确定价格阶段
      dictData: '',
      statusBarHeight: 0,
      barOpacity: 0, // 导航栏透明度
      showPop: false,
      offerPriceConfirmSuggestion: ''
    }
  },
  computed: {
    // 进度描述
    progressDesc() {
      const { latestStageRecord = '', stage = '' } = this.detailInfo
      const handlerStaff = latestStageRecord && latestStageRecord.handlerStaff || ''
      const afterStage = latestStageRecord && latestStageRecord.afterStage || stage

      return handlerStaff + '将订单流转到：' + this.getDictName('CRM_PURCHASE_ORDER_STATUS', afterStage)
    },
    // 采购类型
    isUpSample() {
      const { isUpSample = '' } = this.detailInfo
      return this.getDictName('CRM_PURCHASE_TYPE', isUpSample.toString())
    },
    headerBgColor() {
      return `rgba(250, 251, 254, ${this.barOpacity > 1 ? 1 : this.barOpacity})`
    }
  },
  async created() {
    const { id } = this.$route.query

    await this.initDetail(id)
    this.initProduct(id)
    this.isDealer = await havePosition({ positionCode: 'top_dis' }) // 是否是经销商
    const { stage } = this.detailInfo
    this.isEdit = stage === 'DealerPriceConfirm' && this.isDealer // 经销商确定价格阶段

    const { statusBarHeight } = this.$store.getters
    this.statusBarHeight = statusBarHeight

    const dictTypeCodes = ['CRM_PURCHASE_ORDER_STATUS', 'CRM_PURCHASE_TYPE', 'CRM_CATEGORY_SELECTION']
    this.dictData = await getDictByPatchType({ dictTypeCodes })
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, { passive: true })
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll, { passive: true })
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/purorder') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  methods: {
    // 是否数据转换
    whetherName(val) {
      const map = {
        0: '否',
        1: '是'
      }
      return map[val] || ''
    },
    // 获取数据字典值对应的名称
    getDictName(dictType, dictCode) {
      let name = ''
      if (this.dictData && this.dictData[dictType]) {
        const index = this.dictData[dictType].findIndex(v => v.dictCode === dictCode)
        if (index > -1) {
          name = this.dictData[dictType][index].dictName
        }
      }
      return name
    },
    // 获取送达方
    initSDF() {
      const { shopCode } = this.detailInfo
      querySdf({ storeCode: shopCode }).then(res => {
        if (res.success === 1 && res.data) {
          this.sdfAccount = res.data
        }
      })
    },
    // 获取采购订单详情
    async initDetail(id) {
      const res = await getOrderDetail(id)
      if (res.success === 1 && res.data) {
        this.detailInfo = res.data
        if (this.detailInfo.isUpSample === 1) {
          // 上样订单确认价格时，判断 isPriceOutsourcing 值：
          // 是否锁定(isSapLock)为‘否’时,‘是否需要提前进行外购件采购’默认为‘是’且不可修改,
          // 是否锁定为‘是’时，‘是否提前进行外购件采购’默认为空，需要经销商手工选择后才能确认价格
          if (this.detailInfo.stage === 'DealerPriceConfirm') {
            this.isPriceOutsourcing = this.detailInfo.isSapLock !== 1 ? 1 : ''
          } else {
            this.isPriceOutsourcing = this.detailInfo.isPriceOutsourcing
          }
        } else {
          this.isPriceOutsourcing = 0
        }
        // this.isPriceOutsourcing = this.detailInfo.isPriceOutsourcing || 0
      }
    },
    // 获取产品相关数据
    initProduct(id) {
      const otherFilters = [{ id: 'orderId', property: 'orderId', operator: '=', value: id }]
      const data = json2FormData({
        filtersRaw: JSON.stringify(otherFilters),
        pageFlag: false
      })
      getOrderProductList(data).then(res => {
        if (res.success && res.data) {
          this.productList = res.data.records || []
        }
      })
    },
    handleHeadHeight(h) {
      this.headHeight = h
    },
    // 跳转到进度详情
    jumpToProgressDetail() {
      const { id, stage } = this.detailInfo
      this.$router.push({
        path: '/purOrder/detail/progress',
        query: { id: id, state: stage }
      })
    },
    // 跳转到报价明细页面
    jumpToQuoteDetail(row) {
      const { kjlAuditId, orderId, partNumber, cdsTotalPrice } = row
      this.$router.push({
        path: '/purOrder/detail/plate',
        query: {
          orderId,
          id: kjlAuditId,
          partNumber: partNumber,
          receiptNumber: this.detailInfo.receiptNumber,
          price: cdsTotalPrice }
      })
    },
    // 经销商订单价格确认
    handlePriceConfirm(val) {
      if (this.submiting) return
      if (![1, 0].includes(this.isPriceOutsourcing)) {
        this.$toast('请先选择是否提前进行外购件采购')
        return
      }
      const data = {
        'isPriceOutsourcing': this.isPriceOutsourcing,
        'offerPriceConfirmStatus': val,
        // 'offerPriceConfirmSuggestion': '',
        'orderId': this.detailInfo.id
      }
      if (val === 1) {
        this.$dialog.confirm({
          title: '提示',
          message: '是否确认通过?'
        }).then(() => {
          this.submiting = true
          priceConfirm(data).then(res => {
            if (res.success === 1) {
              bus.$emit('refreshCustomerItem', {
                title: '确认价格',
                type: 'confirm'
              })
              this.$router.go(-1)
            }
            this.submiting = false
          }).catch(e => {
            this.submiting = false
          })
        })
      } else {
        this.showPop = true
      }
    },
    // 经销商订单价格确认 不通过时
    handlePriceFail(val) {
      if (this.submiting) return
      if (![1, 0].includes(this.isPriceOutsourcing)) {
        this.$toast('请先选择是否提前进行外购件采购')
        return
      }
      const data = {
        'isPriceOutsourcing': this.isPriceOutsourcing,
        'offerPriceConfirmStatus': -1,
        'offerPriceConfirmSuggestion': val,
        'orderId': this.detailInfo.id
      }

      this.submiting = true
      priceConfirm(data).then(res => {
        if (res.success === 1) {
          this.offerPriceConfirmSuggestion = ''
          bus.$emit('refreshCustomerItem', {
            title: '确认价格',
            type: 'confirm'
          })
          this.$router.go(-1)
        }
        this.submiting = false
      }).catch(e => {
        this.submiting = false
      })
    },
    // 滑动时改变颜色透明度
    handleScroll() {
      const topEl = document.querySelector(`#oHeader`)
      if (topEl) {
        const top = topEl.getBoundingClientRect().top
        if (top >= 0) {
          this.barOpacity = 0
          return
        }
        let barOpacity = 1 - (top + this.statusBarHeight) / this.statusBarHeight
        if (barOpacity > 1) barOpacity = 1
        this.barOpacity = barOpacity
      }
    }
  }
}
</script>
<style lang="less" scoped>
.pb58 {
  padding-bottom: 58px !important;
}

.content {
  background-image: url('~@/assets/order-detail-bg.png');
  background-repeat: no-repeat;
  background-size: 100% auto;
}
.detail-item {
  padding: 10px 16px 16px 16px;

  .d-progress {
    padding: 10px 12px;
    background: #FFFFFF;
    border-radius: 12px;
    margin-bottom: 10px;
  }
  .d-price {
    padding: 10px 12px;
    background: #FFFFFF;
    border-radius: 12px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .d-fee {
      font-size: 14px;
      font-weight: 500;
      color: #F18548;
      line-height: 20px;
    }
  }
  .d-base {
    padding: 16px;
    background: #FFFFFF;
    border-radius: 8px;
    margin-bottom: 10px;

    .d-base-head {
      position: relative;
      height: 36px;

      &::after{
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        height: 1px;
        background: #EFF2F7;
      }
    }
    .d-base-con {
      padding-top: 16px;

      .d-base-con-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
        &:nth-last-of-type(1) {
          margin-bottom: 0;
        }

        .d-radio {
          /deep/ .van-radio {
            flex-direction: row-reverse;
          }
          /deep/ .van-radio--horizontal {
            margin-right: 30px;
            &:nth-last-of-type(1) {
              margin-right: 0;
            }
          }
          .d-radio-title {
            margin-right: 6px;
          }
        }
      }

      .d-base-btn {
        border-radius: 10px;
        border: 1px solid #16BC83;
        font-size: 14px;
        font-weight: 400;
        color: #16BC83;
        line-height: 34px;
        padding: 0 12px;
      }
    }
  }
  .d-mb10 {
    margin-bottom: 10px;
  }
  .d-title {
    font-size: 14px;
    font-weight: 500;
    color: #3C4458;
    line-height: 20px;
    margin-right: 10px;
    min-width: 70px;
  }
  .d-desc {
    font-size: 14px;
    font-weight: 400;
    color: #7D8091;
    line-height: 20px;
  }

  .d-title-small {
    font-size: 12px;
    font-weight: 500;
    color: #3C4458;
    line-height: 17px;
  }

  .d-desc-small {
    font-size: 12px;
    font-weight: 400;
    color: #7D8091;
    line-height: 17px;
  }
  .d-red {
    color: #F32B14;
  }
  .img-icon {
    width: 18px;
    height: 18px;
  }
  .d-flex {
    display: flex;
    align-items: center;
  }

  .d-btn-con {
    position: fixed;
    bottom: 10px;
    display: flex;
    justify-content: space-between;
    height: 48px;
    width: calc(100vw - 32px);
    .d-btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #16BC83;
      border-radius: 12px;
      font-size: 16px;
      font-weight: 600;
      color: #FFFFFF;
      line-height: 22px;

      &:nth-of-type(1) {
        background: #FF634C;
        margin-right: 15px;
      }
    }
  }
}

</style>
